package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import po.Result;
import service.AdminService;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/login")
    public  String login() {
        //返回登录界面视图
        return "admin/login";
    }

    @RequestMapping("/loginSubmit")
    //登录请求处理
    public @ResponseBody Result loginSubmit(HttpSession session, String username, String password) throws Exception {
        Result result = new Result();
        String pwd = adminService.findPwdByUsername(username);
        if (pwd != null) {
            if (pwd.equals(password)) {
                session.setAttribute("adminName", username);
                result.setResult("success");
                result.setMessage("index");
                return result;
            }
            //密码错误，返回error
            result.setResult("error");
            return result;
        }
        //用户名不存在，返回null
        result.setResult("null");
        return result;
    }

    @RequestMapping("/logout")
    //登出请求处理
    public String logout(HttpSession session) {
        session.invalidate();
        //登出之后返回到登录界面
        return "redirect:login";
    }

    @RequestMapping("/index")
    public String index(HttpSession session) {
        //如果用户未登录就进行拦截，重定向到登录界面
        if (session.getAttribute("adminName") == null) {
            return "redirect:login";
        } else {
            //如果已经登录，则返回主界面视图
            return "admin/index";
        }
    }

    @RequestMapping("/getUpdatePwdView")
    //返回修改密码界面视图
    public String getUpdatePwdView() {
        return "admin/updatePwd";
    }

    @RequestMapping("/updatePwd")
    //修改密码请求处理
    public @ResponseBody Result updatePwd(HttpSession session, String oldPwd, String newPwd) throws Exception {
        return adminService.updatePwdByUsername((String) session.getAttribute("adminName"), oldPwd, newPwd);
    }
}
